package edu.xmut.kakamusic.fragment.mine;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.module.BaseLoadMoreModule;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import edu.xmut.kakamusic.R;
import edu.xmut.kakamusic.activity.MusicPlayerActivity;
import edu.xmut.kakamusic.adapter.mine.MineMusicAdapter;
import edu.xmut.kakamusic.bean.entity.Music;
import edu.xmut.kakamusic.bean.form.MusicPlayForm;
import edu.xmut.kakamusic.bean.vo.HotSongVO;
import edu.xmut.kakamusic.bean.vo.UserInfoVO;
import edu.xmut.kakamusic.databinding.FragmentMineBinding;
import edu.xmut.kakamusic.utils.ApiResponse;
import edu.xmut.kakamusic.utils.Constants;
import edu.xmut.kakamusic.utils.RequestUtils;
import edu.xmut.kakamusic.utils.SPUtils;
import edu.xmut.kakamusic.utils.SnackBarUtil;
import edu.xmut.kakamusic.utils.ToastUtils;
import edu.xmut.kakamusic.utils.WindowUtils;
import edu.xmut.kakamusic.viewmodel.mine.MineMusicViewModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MineFragment extends Fragment {

    private static final String TAG = MineFragment.class.getSimpleName();
    private MineMusicViewModel mineMusicViewModel;
    private MineMusicAdapter mineMusicAdapter;
    private edu.xmut.kakamusic.databinding.FragmentMineBinding binding;
    private Integer currentPage = 1;
    private final Integer pageSize = 20;
    private BaseLoadMoreModule loadMoreModule;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMineBinding.inflate(inflater, container, false);
        mineMusicViewModel = new ViewModelProvider(this).get(MineMusicViewModel.class);
        // 设置状态栏高度
        Toolbar toolbar = binding.mineToolbar;
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams();
        params.topMargin = WindowUtils.getStatusBarHeight(requireContext()) + 20;
        toolbar.setLayoutParams(params);

        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.menu_baidu_map:
                    ToastUtils.show(requireContext(), "打开百度地图");
                    Navigation.findNavController(toolbar)
                            .navigate(R.id.action_menu_mine_to_mapFragment);
                    break;
                case R.id.menu_edit_intro:
                    ToastUtils.show(requireContext(), "编辑简介");
                    break;
                default:
                    break;
            }
            return true;
        });
        // 初始化音乐列表
        RecyclerView recyclerView = binding.recyclerviewMine;
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        mineMusicAdapter = new MineMusicAdapter();
        recyclerView.setAdapter(mineMusicAdapter);
        mineMusicAdapter.setAnimationEnable(true);
        mineMusicAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.ScaleIn);
        mineMusicAdapter.setAnimationFirstOnly(false);

        initEvent();
        return binding.getRoot();
    }

    private void initEvent() {
        // 设置项点击事件
        mineMusicAdapter.setOnItemClickListener((adapter, view, position) -> {
            HotSongVO hotSongVO = (HotSongVO) adapter.getItem(position);
            Log.d(TAG, "initEvent: " + hotSongVO);
            MusicPlayForm musicPlayForm = new MusicPlayForm(
                    hotSongVO.getId(),
                    "standard",
                    hotSongVO.getName(),
                    hotSongVO.getDt(),
                    hotSongVO.getPublishTime(),
                    hotSongVO.getAr().get(0).getId(),
                    hotSongVO.getAl().getId(),
                    hotSongVO.getMv());
            Intent intent = new Intent(requireContext(), MusicPlayerActivity.class);
            intent.putExtra(Constants.MUSIC_PLAY_REQUEST, musicPlayForm);
            startActivity(intent);
        });
        // 设置加载更多
        loadMoreModule = mineMusicAdapter.getLoadMoreModule();
        loadMoreModule.setAutoLoadMore(true);
        loadMoreModule.setEnableLoadMoreIfNotFullPage(false);
        loadMoreModule.setOnLoadMoreListener(() -> {
            if (currentPage * pageSize <= 200) {
                getSongList(currentPage, pageSize);
                currentPage++;
            } else {
                loadMoreModule.loadMoreEnd();
            }
        });
    }


    private void getSongList(Integer currentPage, Integer pageSize) {
        SPUtils spUtils = new SPUtils(requireContext());
        String token = spUtils.getString("token");
        mineMusicViewModel.getHosSong(token, currentPage, pageSize).observe(getViewLifecycleOwner(), response -> {
            if (Objects.nonNull(response) && Objects.equals(response.getCode(), 200)) {
                List<HotSongVO> data = response.getData();
                mineMusicAdapter.addData(data);
                Log.d(TAG, "getHosSong: " + data);
                loadMoreModule.loadMoreComplete();
            } else {
                loadMoreModule.loadMoreFail();
                SnackBarUtil.showSnackBar(requireActivity(), getView(),
                        "获取音乐列表失败", true, 0, null);
            }
        });
    }


    private void getUserInfoData() {
        SPUtils spUtils = new SPUtils(requireContext());
        String token = spUtils.getString("token");
        mineMusicViewModel.getUserInfo(token).observe(getViewLifecycleOwner(), response -> {
            if (Objects.nonNull(response) && Objects.equals(response.getCode(), 200)) {
                UserInfoVO data = response.getData();
                setUserInfo(data);
                Log.d(TAG, "getUserInfo: " + data);
            } else {
                SnackBarUtil.showSnackBar(requireActivity(), getView(),
                        "获取用户信息失败", true, 0, null);
            }
        });
    }

    private void setUserInfo(UserInfoVO data) {
        binding.tvMineNickname.setText(data.getNickname());
        binding.tvMineUserId.setText(String.format("咔咔号: " + data.getPhone()));
        binding.tvMineUserIp.setText(String.format("IP: " + data.getIp()));
        Glide.with(requireContext())
                .load(data.getAvatar())
                .into(binding.circleImageView);
        Glide.with(requireContext())
                .load(data.getBackgroundImage())
                .into(binding.ivMineAppBarBackground);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        // 获取数据
        getUserInfoData();
        // 获取音乐列表
        getSongList(currentPage++, pageSize);
    }
}